package com.hankol.community

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.RecycleViewManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.baselibrary.activity.BaseActivity
import com.hankol.community.adapter.DynamicSearchTopicNewAdapter
import com.hankol.community.adapter.DynamicSearchTopicTabNewAdapter
import com.hankol.community.adapter.TopicMenuNewAdapter
import com.hankol.community.bean.SearchTopicBean
import com.hankol.community.bean.TopicClassifyBean
import com.hankol.community.databinding.ActivityAllTopicBinding
import com.hankol.community.viewmodel.CommunityViewModel
import com.liaoinstan.springview.widget.SpringView
import com.liaoinstan.springview.widget.SpringView.OnFreshListener
import java.util.HashMap

/**
 * 全部话题（首页大改版）
 */
@Route(path = ActivityRouter.COMMUNITY.ALL_TOPIC)
class AllTopicActivity : BaseActivity(), TextWatcher, View.OnClickListener {
    private lateinit var mBinding: ActivityAllTopicBinding
    private var mTopicListAdapter: DynamicSearchTopicNewAdapter? = null
    private lateinit var mViewModel: CommunityViewModel

    private var isRefresh = false
    private var mPageCount = 0
    private val mAllList: MutableList<SearchTopicBean> = ArrayList()
    private val mPageList: MutableList<SearchTopicBean> = ArrayList()
    private var mLastFriendsName: String? = null
    private var mDynamicSearchTopicTabAdapter: DynamicSearchTopicTabNewAdapter? = null
    private var mTopicMenuAdapter: TopicMenuNewAdapter? = null
    private var mTopicMenu: MutableList<TopicClassifyBean> = mutableListOf()
    private var mTopicMenuPos = -1
    private var selectedTagId = -2
    override fun getLayoutId(): Int {
        return R.layout.activity_all_topic
    }

    override fun init() {
        setStatusBarHeight(R.color.white)
        mBinding = getDataBinding<ActivityAllTopicBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)
        initData()
        initObserver()
        initListener()
        SensorsDataManager.instance.allTalkView()
    }

    private fun initObserver() {
        mViewModel.topicTagListLD.observe(this, Observer {
            mTopicMenu = it.toMutableList()
            if (selectedTagId != -2) {
                mTopicMenu.forEachIndexed { index, topicClassifyBean ->
                    if (topicClassifyBean.id == selectedTagId) {
                        mTopicMenuPos = index
                    }
                }
                if (mTopicMenuPos == -1) {//如果话题被冻结了，遍历中没有
                    mTopicMenuPos = 0
                }
            } else {
                mTopicMenuPos = 0
            }
            mTopicMenu[mTopicMenuPos].isSelect = true
            mTopicMenuAdapter!!.setNewData(mTopicMenu)
            mDynamicSearchTopicTabAdapter?.setData(mTopicMenu)
            mBinding.vpSearchTopicList.currentItem = mTopicMenuPos
        })
        mViewModel.searchTopicLD.observe(this, Observer {
            mBinding.svSearchtopic.onFinishFreshAndLoad()
            if (TextUtils.isEmpty(mBinding.edtSearchtopic.text.toString())) {
                //因为网络回执是异步的，所以需要先判断内容框是否还是属于搜索状态
                mBinding.llTopicMenu.visibility = View.VISIBLE
                mBinding.svSearchtopic.visibility = View.GONE
                return@Observer
            }
            if (it != null && it.size > 0) {
                mBinding.tvSearchtopicEmpty.visibility = View.GONE
                mBinding.svSearchtopic.visibility = View.VISIBLE
                mAllList.clear()
                mAllList.addAll(it)
                setPageList()
            } else {
                mBinding.svSearchtopic.visibility = View.GONE
                mBinding.tvSearchtopicEmpty.visibility = View.VISIBLE
                mPageCount = 0
            }
        })
    }

    private fun initData() {
        intent.extras?.let {
            selectedTagId = it.getInt(IntentKey.DEFAULT_TOPIC_TAG_ID, -2)
        }
        mTopicListAdapter = DynamicSearchTopicNewAdapter()
        mDynamicSearchTopicTabAdapter = DynamicSearchTopicTabNewAdapter(supportFragmentManager)
        mTopicMenuAdapter = TopicMenuNewAdapter()
        mBinding.rvSearchtopicList.adapter = mTopicListAdapter
        mTopicListAdapter?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val topicBean = adapter.data[position] as SearchTopicBean
            if (topicBean.checkNotNull()) {
                //跳转话题详情
                KeyBoardUtils.hideShowKeyboard(this)
                val hashMap = HashMap<String, Any>()
                hashMap["tid"] = topicBean.id
                hashMap["tsource"] = "全部话题"
                ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_DETAIL, hashMap)
            }
        }
        mBinding.rvSearchTopicTab.adapter = mTopicMenuAdapter
        mBinding.vpSearchTopicList.adapter = mDynamicSearchTopicTabAdapter
        getAllTopicTags()
    }

    private fun initListener() {
        mBinding.ivBack.setOnClickListener(this)
        mBinding.edtSearchtopic.addTextChangedListener(this)
        mBinding.ivSearchtopicSearch.setOnClickListener(this)
        mBinding.llSearchtopicEmpty.setOnClickListener(this)
        mBinding.svSearchtopic.header = SpringViewNewHeader(applicationContext)
        mBinding.svSearchtopic.footer = SpringViewNewFooter(applicationContext)
        mBinding.svSearchtopic.type = SpringView.Type.FOLLOW
        mBinding.edtSearchtopic.setOnEditorActionListener { textView: TextView?, i: Int, keyEvent: KeyEvent? ->
            //隐藏软键盘
            @SuppressLint("WrongConstant") val imm = getSystemService("input_method") as InputMethodManager
            imm.toggleSoftInput(0, 2)
            if (TextUtils.isEmpty(mBinding.edtSearchtopic.text.toString())) {
                HKToastUtils.showToast("请输入搜索关键字")
                getTopicsList("", true)
            } else {
                getTopicsList(mBinding.edtSearchtopic.text.toString(), false)
            }
            true
        }
        mBinding.svSearchtopic.setListener(object : OnFreshListener {
            override fun onRefresh() {
                isRefresh = true
                getTopicsList(mLastFriendsName, TextUtils.isEmpty(mLastFriendsName))
            }

            override fun onLoadmore() {
                isRefresh = false
                setPageList()
            }
        })
        mTopicMenuAdapter?.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            mTopicMenuPos = position
            for (i in mTopicMenu!!.indices) {
                mTopicMenu!![i].isSelect = i == position
            }
            mTopicMenuAdapter?.setNewData(mTopicMenu)
            mBinding.vpSearchTopicList.currentItem = position
        }
        mBinding.vpSearchTopicList.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {
                if (mTopicMenuPos == position) {
                    mTopicMenuPos = -1
                    //执行setCurrentItem这里也会回掉，所以 下标一样的情况下不做操作
                    return
                }
                for (i in mTopicMenu!!.indices) {
                    mTopicMenu!![i].isSelect = i == position
                }
                mTopicMenuAdapter?.setNewData(mTopicMenu)
                RecycleViewManager.smoothMoveToPosition1(mBinding.rvSearchTopicTab, position)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun afterTextChanged(editable: Editable) {
        if (editable.toString().length <= 0) {
            mBinding.llSearchtopicEmpty.visibility = View.GONE
            mBinding.svSearchtopic.visibility = View.GONE
            mBinding.tvSearchtopicEmpty.visibility = View.GONE
            getTopicsList(editable.toString(), true)
        } else {
            mBinding.llSearchtopicEmpty.visibility = View.VISIBLE
            getTopicsList(editable.toString(), false)
        }
    }

    fun getTopicsList(friendsName: String?, isDef: Boolean) {
        mBinding.llTopicMenu.visibility = View.GONE
        mLastFriendsName = friendsName
        mPageList.clear()
        if (isDef) {
            mBinding.llTopicMenu.visibility = View.VISIBLE
            mBinding.svSearchtopic.visibility = View.GONE
        } else {
            mViewModel.requestSearchTopicByName(friendsName.checkValue(),1)
        }
    }

    private fun getAllTopicTags() {
        mViewModel.requestTopicTagList(1)

    }

    override fun onClick(view: View) {
        val id = view.id
        if (id == R.id.iv_back) {
            finish()
        } else if (id == R.id.iv_searchtopic_search) {
            if (TextUtils.isEmpty(mBinding.edtSearchtopic.text.toString())) {
                getTopicsList("", true)
                return
            }
            getTopicsList(mBinding.edtSearchtopic.text.toString(), false)
        } else if (id == R.id.ll_searchtopic_empty) {
            mBinding.llSearchtopicEmpty.visibility = View.GONE
            mBinding.tvSearchtopicEmpty.visibility = View.GONE
            mBinding.edtSearchtopic.setText("")
            getTopicsList("", true)
        }
    }

    private fun setPageList() {
        if (isRefresh) { //这里的清空貌似没啥用
            mPageList.clear()
            mPageCount = 0
        }
        val mPageSize = mPageList.size
        val mAllSize = mAllList.size
        if (mPageSize >= mAllSize) {
            mBinding.svSearchtopic.onFinishFreshAndLoad()
            //            ToastUtil.toastShortMessage("已经全部加载完成");
            return
        }
        for (i in mPageSize until mAllSize) {
            if (mPageCount == 20) {
                mBinding.svSearchtopic.onFinishFreshAndLoad()
                break
            }
            mPageCount += 1
            mPageList.add(mAllList[i])
            if (mPageList.size == mAllSize) {
                mBinding.svSearchtopic.onFinishFreshAndLoad()
                //ToastUtils.showShort(this, "已经全部加载完成")
                break
            }
        }
        mTopicListAdapter?.setNewData(mPageList)
        mTopicListAdapter?.notifyDataSetChanged()
        mPageCount = 0
    }
}